<template>
  <section class="decoration-edit">
    <section class="l">
      <ul @dragstart="dragStart" @dragend="dragEnd">
        <li
          v-for="(val, key, index) in typeList"
          :draggable="true"
          :data-type="key"
          :key="index + 1"
        >
          <!-- <span :class="val.icon"></span> -->
          <Icon :icon="val.icon" />
          <p>{{ val.name }}</p>
        </li>
      </ul>
    </section>
    <section class="c">
      <!-- header 不可拖拽 -->
      <!-- @click="selectType(0)" -->
      <div class="top-nav">
        <img src="../../../assets/images/topNavBlack.png" />
        <span class="tit">登陆</span>
      </div>
      <div class="view-content" @drop="drog" @dragover="dragOver">
        <!-- :style="{ backgroundColor: info.backgroundColor }" -->
        <Draggable :list="view">
          <template #item="{ element, index }">
            <div class="item" @click="selectType(index)">
              <div class="wait" v-if="element.status && element.status == 2">{{
                element.type
              }}</div>
              <div v-else>
                <component
                  :is="typeList[element.type]['com']"
                  :data="element"
                  :className="className[element.tabType]"
                ></component>
              </div>
              <p @click="deleteItem($event, index)" class="el-icon-error">
                <Icon icon="simple-line-icons:close" />
              </p>
              <!-- <i @click="deleteItem($event, index)"  class="el-icon-error"></i> -->
            </div>
          </template>
        </Draggable>
      </div>
    </section>
    <section class="r">
      <EditForm :data="props" v-if="isRight"></EditForm>
    </section>

    <div class="submit-btn">
      <el-button @click="submit">提交页面</el-button>
    </div>
  </section>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsShopAppsetLoginList',
  });
</script>

<script lang="ts" setup>
  import { Icon } from '/@/components/Icon';
  import Draggable from 'vuedraggable';
  import EditForm from '/@/components/Edit/index.vue';
  // import Product from '/@/components/View/Product.vue';
  // import Images from '/@/components/View/Images.vue';
  // import Banner from '/@/components/View/Banner.vue';
  import Login from '/@/components/View/login.vue';
  import { ElMessage } from 'element-plus';
  import { reactive, ref, computed, nextTick, defineComponent, onMounted } from 'vue';
  import { shopForm, shopSave } from '/@/api/shop/shop';
  import { useGlobSetting } from '/@/hooks/setting';
  const { ctxPath } = useGlobSetting();

  let typeList = reactive({
    // banner: {
    //   name: '轮播图',
    //   icon: 'simple-line-icons:picture',
    //   com: Banner,
    // },
    // product: {
    //   name: '商品',
    //   icon: 'simple-line-icons:briefcase',
    //   com: Product,
    // },
    // images: {
    //   name: '图片',
    //   icon: 'simple-line-icons:picture',
    //   com: Images,
    // },
    login: {
      name: '背景图',
      icon: 'simple-line-icons:picture',
      com: Login,
    },
  });
  let view: any = reactive([]);
  let title: any = ref('页面标题');
  let type: any = ref('');
  let id: any = ref('');
  let index: any = ref(null);
  let isPush = ref(false);
  let props: any = reactive({});
  let className: any = reactive({
    1: 'one',
    2: 'two',
    3: 'three',
  });
  let isRight: any = ref(false);
  const info = computed(() => {
    // return view[0];
    return {
      type: 'info',
      title: '页面标题',
    };
  });
  async function listData() {
    const res = await shopForm();
    console.log(ctxPath, '=======ctxPath');

    id.value = res.shopAppsetLogin.id;
    if (!res.shopAppsetLogin.isNewRecord) {
      index.value = view.length;
      isPush.value = true;
      view.push({
        data: [
          {
            name: res.shopAppsetLogin.name,
            url: ctxPath + res.shopAppsetLogin.curl,
            form: '',
            fileUpload :{
              fileName:res.shopAppsetLogin.name,
              fileUrl:res.shopAppsetLogin.curl,
              id:res.shopAppsetLogin.fileId
            }
          },
        ],
        options: {},
        status: '',
        type: 'login',
      });
    }

    console.log(view, 'view======');
  }
  listData();

  async function submit() {
    // JSON 转换会丢失 formData
    const form = JSON.parse(JSON.stringify(view));

    if (form.length == 0) {
      ElMessage.error('请添加模块！');
      return;
    }

    for (let i of form) {
      if (i.data && i.data.length == 0) {
        ElMessage.error('请填写完整信息！');
        return;
      }
      if (i.type === 'product') {
        i.data = i.data.map((val) => val.productId).join(',');
      }
    }
    // console.log(form); // 提交的数据，根据接口形式修改
    try {
      let params = {
        name: form[0].data[0].fileUpload.fileName,
        curl: form[0].data[0].fileUpload.fileUrl,
        fileId: form[0].data[0].fileUpload.id,
        id: id.value,
      };
      const res = await shopSave(params);
      console.log(res);
      ElMessage.success(res.message);
    } catch (error: any) {
      if (error || error.errorFields) {
        ElMessage.error('保存失败！');
      }
      console.log('error', error);
    } finally {
    }
  }

  function selectType(index) {
    console.log(index, 'selectType==');

    isRight.value = false;
    props = view[index];
    nextTick(() => (isRight.value = true));
  }
  function deleteItem(e, index) {
    console.log(index, e, '删除======');

    e.preventDefault();
    e.stopPropagation();
    view.splice(index, 1);
    isRight.value = false;
    props = {};
  }
  function dragStart(e) {
    type.value = e.target.dataset.type;
  }
  function dragEnd() {
    view.forEach((item) => {
      item['status'] = '';
    });
    // view[index.value]['status'] = ''
    // delete view[index.value]['status'];
    // $delete(view[index.value], 'status');
    isPush.value = false;
    type.value = null;
  }
  function drog(e) {
    if (!type.value) {
      // 内容拖拽
      return;
    }
    e.preventDefault();
    e.stopPropagation();
    dragEnd();
  }
  function dragOver(e) {
    // console.log(e.target.__draggable_context,'1111111111111dragOver');

    if (!type.value) {
      // 内容拖拽
      return;
    }
    e.preventDefault();
    e.stopPropagation();

    let className = e.target.className;
    let name = className !== 'view-content' ? 'item' : 'view-content';

    let defaultData = {
      type: type.value, // 组件类型
      status: 2, // 默认状态
      data: [], // 数据
      options: {}, // 选项操作
    };

    if (name == 'view-content') {
      if (!isPush.value) {
        index.value = view.length;
        isPush.value = true;
        view.push(defaultData);
      }
    } else if (name == 'item') {
      let target = e.target;
      let [y, h, curIndex] = [e.offsetY, target.offsetHeight, target.__draggable_context.index];
      let direction = y < h / 2;

      if (!isPush.value) {
        // Push to Top or Bottom
        if (direction) {
          if (curIndex == 0) {
            view.unshift(defaultData);
          } else {
            view.splice(curIndex, 0, defaultData);
          }
        } else {
          curIndex = +curIndex + 1;
          view.splice(curIndex, 0, defaultData);
        }
      } else {
        // Moving
        if (direction) {
          var i = curIndex == 0 ? 0 : curIndex - 1;
          var result = view[i]['status'] == 2;
        } else {
          var i = +curIndex + 1;
          var result = view.length > i && view[i]['status'] == 2;
        }

        if (result) return;

        const temp = view.splice(index.value, 1);
        view.splice(curIndex, 0, temp[0]);
      }
      index.value = curIndex;
      isPush.value = true;
    }
  }
</script>
<style lang="less">
  .decoration-edit {
    display: flex;
    align-items: center;
    justify-content: space-between;
    // padding: 10px 0;
    background: #f7f8f9;
    height: calc(100vh - 120px);
    position: relative;
    .l,
    .r {
      width: 340px;
      height: 100%;
      padding: 15px 0;
      background: #fff;
    }
    .l {
      ul {
        margin: 0;
        padding: 0;
        li {
          width: 80px;
          height: 80px;
          display: flex;
          justify-content: center;
          align-items: center;
          flex-direction: column;
          cursor: default;
          list-style: none;
          font-size: 14px;
          color: #666;
          float: left;
          margin: 0 10px;
          border-radius: 6px;
          transition: all 0.3s;
          cursor: pointer;
          &:hover {
            background: #efefef;
          }
          span {
            display: block;
            font-size: 40px;
            margin-bottom: 8px;
            color: #999;
          }
          p {
            display: block;
            margin: 0;
            font-size: 12px;
          }
        }
      }
    }
    .c {
      width: auto;
      max-width: 400px;
      position: relative;
      .top-nav {
        position: absolute;
        top: 0;
        background: #fff;
        z-index: 999;
        transition: all 0.3s;
        & * {
          pointer-events: none;
        }
        &:hover {
          transform: scale(0.95);
          border-radius: 10px;
          overflow: hidden;
          box-shadow: 0 0 10px #afafaf;
        }
        .tit {
          position: absolute;
          left: 50%;
          bottom: 10px;
          transform: translateX(-50%);
        }
        img {
          max-width: 100%;
          image-rendering: -moz-crisp-edges;
          image-rendering: -o-crisp-edges;
          image-rendering: -webkit-optimize-contrast;
          image-rendering: crisp-edges;
          -ms-interpolation-mode: nearest-neighbor;
        }
      }
      .view-content {
        width: 400px;
        height: 700px;
        background: #f5f5f5;
        overflow-y: auto;
        overflow-x: hidden;
        padding-top: 72px;
        box-shadow: 0 2px 6px #ccc;
        &::-webkit-scrollbar {
          width: 6px;
        }
        &::-webkit-scrollbar-thumb {
          background: #dbdbdb;
        }
        &::-webkit-scrollbar-track {
          background: #f6f6f6;
        }

        .item {
          transition: all 0.3s;
          background: #fff;
          &:hover {
            transform: scale(0.95);
            border-radius: 10px;
            box-shadow: 0 0 10px #afafaf;
            .el-icon-error {
              display: block;
            }
          }
          div {
            pointer-events: none;
          }
          .wait {
            background: #deedff;
            height: 35px;
            text-align: center;
            line-height: 35px;
            font-size: 12px;
            color: #666;
          }
          .el-icon-error {
            position: absolute;
            right: 0px;
            top: -6px;
            color: red;
            // background: red;
            font-size: 25px;
            cursor: pointer;
            display: none;
            z-index: 9999;
          }
        }
      }
    }
    .submit-btn {
      position: absolute;
      bottom: 30px;
      left: 50%;
      transform: translateX(-50%);
    }
  }
</style>
